package com.example.fszq.volleydemo1.utils;

import android.content.Context;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.fszq.volleydemo1.CatImgController;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by fszq on 2015/12/2.
 * 此类用于解析c2000服务器返回的html串
 */
public class Parsehtml {
    private String returnstr = "";
    private JSONArray topListJsonArray,catListJsonArray;

    private String htmlFoot  = "</div></div></div></section></body></html>";
    private String htmlCss = "";
    private String htmlHead = "<!DOCTYPE html><html class=\"expanded\"><head><meta charset=\"utf-8\"/><title>title</title><meta id=\"viewport\" name=\"viewport\" content=\"initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no\"><meta name=\"format-detection\" content=\"telephone=no\"><meta name=\"apple-mobile-web-app-capable\" content=\"yes\" /><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" /></head>\n";
    private String htmlReplyHead = "<div class=\"m-reply m-card-split-line\" id=\"J_replyContent\"><div class=\"bright-reply\"><div class=\"title\"><h2>回复内容</h2></div><div class=\"reply-inner\">";
    private int maxPage = 0;
    private String nextStarUserId = "";
    private String postUserId = "";

    public void Parsehtml(){
        //读取本地cssfile
    };

    public JSONArray getTopicList(String htmlStr)  {
        int st = 0,idx = 0,subScript = 0;
        String matchStr = "",tempStr = "",reply = "",nhtmlStr = "";

        String patternStr = "<Script Language=JavaScript>.+?</Script>";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(htmlStr);

        topListJsonArray = new JSONArray();

        while(matcher.find()) {
            matchStr = matcher.group();
            idx = matchStr.indexOf("','");
            st = 0;
            subScript = 0;

            //Log.d("parse",matchStr);
            try{
                JSONObject htmlParseJson = new JSONObject();

                while(idx>0) {
                    tempStr = matchStr.substring(st,idx);
                    st = idx;
                    idx = matchStr.indexOf("','",idx+1);
                    tempStr = tempStr.replace("','","");
                    switch(subScript) {
                        case 0:
                            tempStr = tempStr.replace("<Script Language=JavaScript>document.write (dvbbs_topic_list(TempStr,'","");
                            htmlParseJson.put("topicid",tempStr);
                            break;
                        case 2:
                            htmlParseJson.put("title",tempStr);
                            break;
                        case 3:
                            htmlParseJson.put("author",tempStr);
                            break;
                        case 7:
                            htmlParseJson.put("submitdate",tempStr);
                            break;
                        case 8:
                            reply = tempStr;
                            break;
                        case 9:
                            htmlParseJson.put("viewreply",reply + "/" + tempStr);
                            break;
                    }
                    subScript++;
                }

                topListJsonArray.put(htmlParseJson);
            } catch(Exception e) {
                e.printStackTrace();
            }

        }

        JSONObject jsonObject2 = new JSONObject();
        return topListJsonArray;
    };

    public String getForumStr(String htmlStr,int page) {
        String webData =  "",tempPage = "";
        int st = 0,idx = 0,subScript = 0,forumNum = 0;
        int pst = 0;
        int subjectSt = 0,subjectEn = 0;
        int matchCount = 0;
        String matchStr = "",tempStr = "",htmlDivStr = "",nhtmlStr = "",forumTheme = "";
        String htmlForumHeader = "",htmlForumContent = "";

        String patternStr = "document.write \\(dvbbs_show_topic.+?</Script>";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(htmlStr);

        //获取css文件
        htmlCss = CatImgController.getmInstance().getHtmlCss();

        //获取div
        htmlDivStr = CatImgController.getmInstance().getForumDivCssStr();
        htmlForumContent = CatImgController.getmInstance().getForumContentStr();
        htmlForumHeader = CatImgController.getmInstance().getForumHeaderStr();

        //获取topic标题
        if(page == 1) {
            subjectSt = htmlStr.indexOf("贴子主题");
            subjectEn = htmlStr.indexOf("</th>", subjectSt);
            forumTheme = htmlStr.substring(subjectSt + 5, subjectEn);
        }

        //求出总页数
        if(this.maxPage==0) {
            pst = htmlStr.indexOf("var TopicNum='");
            tempPage = htmlStr.substring(pst + 14, htmlStr.indexOf("'", pst + 14));
            forumNum = Integer.parseInt(tempPage);
            this.maxPage = (int) Math.ceil((float) forumNum / 10);
            Log.d("getforumNum", this.maxPage + "");
        }

        //获取发帖人ID

        webData = htmlHead + htmlCss + "<body>";

        while(matcher.find()) {
                matchStr = matcher.group();
                idx = matchStr.indexOf("','");
                st = 0;
                subScript = 0;

                //
                HashMap<String,String> forumval = new HashMap<String,String>();
                while(idx>0) {
                    tempStr = matchStr.substring(st, idx);
                    st = idx;
                    idx = matchStr.indexOf("','", idx + 3);
                    tempStr = tempStr.replace("','", "");

                    switch(subScript) {
                        case 0:
                            //获取下一页的userid
                                this.nextStarUserId = tempStr.substring(tempStr.indexOf("'") + 1, tempStr.length());
                            //Log.d("getnextuserid",tempStr.substring(0,tempStr.indexOf("'")-1));
                                if(this.postUserId.length()==0) {
                                    this.postUserId = this.nextStarUserId;
                                }
                            break;
                        case 13:
                            //处理图片
                            tempStr = this.getImg(tempStr);
                            //webData = webData + "<div>" + tempStr + "</div><div style='clear:both'></div>";

                            //把那些大字体的html样式去掉

                            tempStr = tempStr.replaceAll("<h.+?>","<b>");
                            tempStr = tempStr.replaceAll("</h.+?>","</b>");
                            tempStr = tempStr.replaceAll("<font.+?>|<FONT.+?>","");
                            tempStr = tempStr.replaceAll("</font>|</FONT>","");
                            tempStr = tempStr.replace("quote","reply-quote-content");
                            Log.d("contentpoc",tempStr);

                            forumval.put("content",tempStr);
                            byte [] encode = Base64.encode(tempStr.getBytes(), Base64.DEFAULT);
                            String enc = new String(encode);
                            forumval.put("base64content",enc);
                            break;
                        case 2:
                            forumval.put("author",tempStr);
                            try {
                                forumval.put("authorencode", java.net.URLEncoder.encode(tempStr, "utf-8"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                        case 8:
                            if(tempStr.indexOf("http")==-1)
                                forumval.put("ulogo","http://www.c2000.cn/" + tempStr);
                            else
                                forumval.put("ulogo",tempStr);

                            break;
                        case 14:
                            forumval.put("submitdate", tempStr);
                            break;
                    }


                    subScript++;
                }

                //处理首页情况
                if(page ==1 && matchCount == 0) { //增加标题头，主贴
                    nhtmlStr = htmlForumHeader + "<section class=\"detail-wrap\">" + htmlForumContent;
                    nhtmlStr = nhtmlStr.replace("forumcontent",forumval.get("content"));
                    nhtmlStr = nhtmlStr.replace("forumtheme",forumTheme);
                    nhtmlStr = nhtmlStr.replace("authorname",forumval.get("author"));
                    nhtmlStr = nhtmlStr.replace("submitdate",forumval.get("submitdate"));
                    nhtmlStr = nhtmlStr + htmlReplyHead;
                    matchCount++;
                } else {
                    nhtmlStr = htmlDivStr;
                    if( matchCount == 0) {
                        nhtmlStr = htmlReplyHead + nhtmlStr;
                    }
                    nhtmlStr = nhtmlStr.replace("ulogo",forumval.get("ulogo"));
                    nhtmlStr = nhtmlStr.replace("authorname",forumval.get("author"));
                    nhtmlStr = nhtmlStr.replace("submitdate",forumval.get("submitdate"));
                    nhtmlStr = nhtmlStr.replace("forumcontent",forumval.get("content"));
                    nhtmlStr = nhtmlStr.replace("base64content",forumval.get("base64content"));
                    nhtmlStr = nhtmlStr.replace("authorencode",forumval.get("authorencode"));
                    matchCount++;
                }

                webData = webData +   nhtmlStr ;


                //清空数组
                forumval.clear();
        }

        webData = webData + htmlFoot;



        return webData;
    };

    //此方法对返回内容中的img url做处理，加上 c2000的网址
    private String  getImg(String htmlStr) {
        String imgData = "",imgUrl = "",patternReplace = "",simgUrl = "";
        String patternStr = "[SRC|src]=\".+?\""; //[jpg|png|gif|jpeg]
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(htmlStr);

        while(matcher.find()) {
            imgUrl = matcher.group();
            Log.d("matchimgurl",imgUrl);

            imgUrl = imgUrl.substring(3, imgUrl.length() - 1);

            if(imgUrl.indexOf("http")==-1) {
                simgUrl = "http://www.c2000.cn/" + imgUrl;
            } else {
                simgUrl = imgUrl;
            }

            imgData = "<img style='max-width:100%' src='"+ simgUrl +"'>";
            //Log.d("matchimgurl",imgData);
            //imgData;
            patternReplace = "<img SRC=\"" + imgUrl + ".+?\">";
            Log.d("patternurl",patternReplace);
            htmlStr = htmlStr.replaceAll(patternReplace,imgData);
        }

        //处理头像图标  Skins/Default/emot/em
        htmlStr = htmlStr.replace("src=Skins/Default/emot/em","src=http://www.c2000.cn/Skins/Default/emot/em");
        htmlStr = htmlStr.replace(".gif border=0 align=middle onmousewheel=\"return bbimg(this)\" onload=\"javascript:if(this.width>screen.width-333)this.style.width=screen.width-333;\"",".gif");
        return htmlStr;
    };

    //此方法返回目录的json数组
    public JSONArray getCatJSON(String htmlStr) {
        String matchStr = "",tempStr = "";
        int idx = 0,st = 0,subScript = 0,matchCount = 0;
        //首先获取所有栏目
        String patternStr = "showboard\\(.+?\\);"; //[jpg|png|gif|jpeg]
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(htmlStr);

        catListJsonArray = new JSONArray();

        while(matcher.find()) {
            matchStr = matcher.group();
            idx = matchStr.indexOf(",'");
            st = 0;
            subScript = 0;

                //Log.d("parse",matchStr);
                try {
                    JSONObject htmlParseJson = new JSONObject();

                    while (idx > 0) {
                        tempStr = matchStr.substring(st, idx);
                        Log.d("tempStr",tempStr);
                        st = idx;
                        idx = matchStr.indexOf(",'", idx + 1);
                        switch (subScript) {
                            case 0: //处理目录cid
                                tempStr = tempStr.replace("showboard(", "");
                                htmlParseJson.put("cid", tempStr);
                                break;
                            case 1: //获取目录名字
                                tempStr = tempStr.substring(2, tempStr.indexOf("'",2));
                                htmlParseJson.put("cname", tempStr);
                                break;
                            case 2: //获取目录介绍
                                tempStr = tempStr.substring(2, tempStr.indexOf("'",2));
                                htmlParseJson.put("cmastr", tempStr);
                                break;
                            case 4: //获取目录图标
                                tempStr = tempStr.substring(2, tempStr.indexOf("'",2));
                                htmlParseJson.put("clogo", "http://www.c2000.cn/" + tempStr);
                                break;
                        }
                        subScript++;
                    }
                    htmlParseJson.put("istitle", "0");
                    htmlParseJson.put("idx", matcher.start() + "");

                    catListJsonArray.put(htmlParseJson);
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }

        st = 0;idx = 0;matchCount = 0;
        //处理title部分
        patternStr = "showclass\\(.+?\\);"; //[jpg|png|gif|jpeg]
        pattern = Pattern.compile(patternStr);
        matcher = pattern.matcher(htmlStr);

        while(matcher.find()) {
            matchStr = matcher.group();
            idx = matchStr.indexOf(",'");
            st = 0;
            subScript = 0;

            //if(matchCount>0) {
                //Log.d("parse",matchStr);
                try {
                    JSONObject htmlParseJson = new JSONObject();

                    while (idx > 0) {
                        tempStr = matchStr.substring(st, idx);
                        Log.d("tempStr",tempStr);
                        st = idx;
                        idx = matchStr.indexOf(",'", idx + 1);
                        switch (subScript) {
                            case 0: //处理目录cid
                                tempStr = tempStr.replace("showclass(", "");
                                htmlParseJson.put("cid", tempStr);
                                break;
                            case 1: //获取目录名字
                                tempStr = tempStr.substring(2, tempStr.indexOf("'",2));
                                htmlParseJson.put("cname", tempStr);
                                break;
                        }
                        subScript++;
                    }
                    htmlParseJson.put("cmastr","");
                    htmlParseJson.put("clogo","");
                    htmlParseJson.put("istitle", "1");
                    htmlParseJson.put("idx", matcher.start() + "");

                    catListJsonArray.put(htmlParseJson);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            //}

            matchCount++;
        }

        Log.d("catlist:",catListJsonArray.toString());
        return catListJsonArray;
    };

    //返回有多少页
    public int getForumMaxPage() {
        return this.maxPage;
    };

    //返回下一页的开始用户id
    public String getNextStarUserId() {
        return this.nextStarUserId;
    }

    //返回发帖人的id
    public String getPostUserId() {
        return this.postUserId;
    }
}
